from OpenSSL import crypto

# 生成CA私钥
ca_key = crypto.PKey()
ca_key.generate_key(crypto.TYPE_RSA, 2048)

# 创建自签名证书
ca_cert = crypto.X509()
ca_cert.get_subject().CN = "Root CA"
ca_cert.set_serial_number(1000)
ca_cert.gmtime_adj_notBefore(0)
ca_cert.gmtime_adj_notAfter(10*365*24*60*60)
ca_cert.set_issuer(ca_cert.get_subject())
ca_cert.set_pubkey(ca_key)
ca_cert.add_extensions([
    crypto.X509Extension(b"basicConstraints", True, b"CA:TRUE"),
    crypto.X509Extension(b"keyUsage", True, b"keyCertSign, cRLSign"),
])
ca_cert.sign(ca_key, "sha256")

# 保存CA证书和私钥
with open("ca.key", "wb") as f:
    f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, ca_key))
with open("ca.crt", "wb") as f:
    f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, ca_cert))

# 生成虚拟机私钥
vm_key = crypto.PKey()
vm_key.generate_key(crypto.TYPE_RSA, 2048)

# 创建证书请求
req = crypto.X509Req()
req.get_subject().CN = "vm.example.com"
req.set_pubkey(vm_key)
req.sign(vm_key, "sha256")

# 用CA签名生成证书
vm_cert = crypto.X509()
vm_cert.set_subject(req.get_subject())
vm_cert.set_serial_number(2000)
vm_cert.gmtime_adj_notBefore(0)
vm_cert.gmtime_adj_notAfter(5*365*24*60*60)
vm_cert.set_issuer(ca_cert.get_subject())
vm_cert.set_pubkey(req.get_pubkey())
vm_cert.add_extensions([
    crypto.X509Extension(b"keyUsage", False, b"digitalSignature, keyEncipherment"),
    crypto.X509Extension(b"extendedKeyUsage", False, b"serverAuth, clientAuth"),
])
vm_cert.sign(ca_key, "sha256")

# 保存虚拟机证书和私钥
with open("vm.key", "wb") as f:
    f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, vm_key))
with open("vm.crt", "wb") as f:
    f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, vm_cert))